package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"member/models"
	"path/filepath"
	"strings"
	"time"
)

type MemTerController struct {
	beego.Controller
}

type JsonMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *MemTerController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	name := c.GetString("name")
	memter, total, err := models.MysqlList(page, pageSize, name)
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		JsonData := make(map[string]interface{})
		JsonData["memter"] = memter
		JsonData["total"] = total
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "分页成功",
			Data: JsonData,
		}
		c.ServeJSON()
	}
}
func (c *MemTerController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件接送失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	if header.Size > 3*1024*1024 {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件必须大于3MB",
			Data: nil,
		}
		c.ServeJSON()
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	suffixMax := map[string]bool{
		".jpg": true,
		".png": true,
	}
	if !suffixMax[suffix] {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件格式不对",
			Data: nil,
		}
		c.ServeJSON()
	}
	path := "/static/img" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		ImgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "上传成功",
			Data: ImgSrc,
		}
		c.ServeJSON()
	}
}
func (c *MemTerController) Show() {
	id, _ := c.GetInt("id")
	var memter models.MemTer
	err := models.DB.Where("id = ?", id).First(&memter).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "展示成功",
			Data: memter,
		}
		c.ServeJSON()
	}
}
func (c *MemTerController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	phone := c.GetString("phone")
	types := c.GetString("types")
	price, _ := c.GetFloat("price", 64)
	times := time.Now()
	emeter := models.MemTer{
		Name:  name,
		Phone: phone,
		Types: types,
		Price: price,
		Times: times,
	}
	err := models.DB.Where("ID = ?", id).Updates(&emeter).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
